<?php

class Admin_UsuarioController extends Zend_Controller_Action {

    private $_debugLog;
    private $_errorLog;

    public function init() {
        /* Initialize action controller here */
        $this->_debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $this->_errorLog = Zend_Registry::get(VirtualLabs_Common::ERROR_LOG);
    }

    public function preDispatch() {
        // Autenticacion del usuario
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_helper->layout->disableLayout();
            $this->_forward("index", "index", "");
        } else {
            $identity = $auth->getIdentity();
            if ($identity['tipo_usuario'] != VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                $this->_helper->layout->disableLayout();
                $this->_redirect('/');
            }
        }
        //fin de la autenicacion del usuario
    }

    public function bulkcsvAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
//        recibimos el archivo
        $adapter = new Zend_File_Transfer_Adapter_Http();
        $this->_debugLog->debug("destination :" . TMP);
        $adapter->setDestination(TMP);

        if (!$adapter->receive()) {
            $messages = $adapter->getMessages();
            echo implode("\n", $messages);
        } else {
            try {
                $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
                $response = array();
                $gestor = @fopen($adapter->getFileName(), "r");
                if ($gestor) {
                    $usuarioDao = new VirtualLabs_Admin_Usuario();
                    $laboratorioDao = new VirtualLabs_Admin_Laboratorio();
                    while (($buff = fgets($gestor, 4096)) !== false) {
                        $row = explode(",", $buff);
                        if (count($row) != 4) {
//                        tiene menos de 4 columnas.. pasar de largo
                            continue;
                        }
                        $data = array('username' => $row[0], 'nombre' => $row[1], 'apellido' => $row[2], 'email' => str_replace("\r\n", "", $row[3]), 'tipo_usuario' => VirtualLabs_Admin_Usuario::ROL_ALUMNO);
//                        print_r($data);
                        $validator = new Zend_Validate_EmailAddress();

                        if ((!$data['nombre']) || !$validator->isValid($data['email']) || (!$data['username'])) {
//                        si el mail es invalido o no hay nombre o no hay username no vale
                            $invalidToString = print_r($data, true);
                            $this->_debugLog->debug("datos invalidos : $invalidToString");
                            continue;
                        } else {
                            $this->_debugLog->debug("Procesando : " . $data['username']);
                            $usuario = $usuarioDao->getUsuario(array('username'), array('username' => array('criteria' => '=', 'value' => $data['username'])));

//                        si no existe
                            if (!$usuario['username']) {
                                $usuarioDao->save(VirtualLabs_Admin_Usuario::TABLE_NAME, $data);
                            }

                            // datos a responder
                            $response[] = $data;

                            // si no esta ya asociado se va a asociar
                            if (!$laboratorioDao->isMemberInLab($data['username'], $codigoLaboratorio, VirtualLabs_Admin_Usuario::ROL_ALUMNO)) {
                                $miembros[] = array('username' => $data['username'], 'rol' => VirtualLabs_Admin_Usuario::ROL_ALUMNO);
                            }
                        }
                    }
                    if (!feof($gestor)) {
                        echo "Error: fallo inesperado de fgets()\n";
                        echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_ERROR));
                        return;
                    }
                    fclose($gestor);
                }
            } catch (Exception $e) {
                $this->_errorLog->err("Error procesando : " . $e->getMessage());
                $this->_errorLog->err($e->getTraceAsString());
            }
            try {
                $laboratorioDao->agregarMiembros($miembros, $codigoLaboratorio);
                echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_SUCCESS, 'alumnos' => $response));
            } catch (Exception $e) {
                $this->_errorLog->err("Error asociando : " . $e->getMessage());
                $this->_errorLog->err($e->getTraceAsString());
                echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_ERROR));
            }
        }
    }

    public function indexAction() {
        
    }

    public function gettiposusuarioAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        echo "<option value='" . VirtualLabs_Admin_Usuario::ROL_ADMIN . "'>Admin</option>"
        . "<option value='" . VirtualLabs_Admin_Usuario::ROL_PROFESOR . "'>Profesor</option>"
        . "<option value='" . VirtualLabs_Admin_Usuario::ROL_ALUMNO . "'>Alumno</option>";
    }

    public function deleteAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        $username = trim($this->getRequest()->getParam('id'));
        $this->_debugLog->info('Deleteing user... ' . $this->getRequest()->getParam('id'));
        $vm = new VirtualLabs_Admin_Usuario();
        try {

//            if ($vm->delete(VirtualLabs_Admin_Usuario::TABLE_NAME, array('key' => 'username', 'value' => $username)))
            if ($vm->save(VirtualLabs_Admin_Usuario::TABLE_NAME, array('estado' => 'I'), array('key' => 'username', 'value' => $username)))
                $this->forward('index');
            else
                echo Zend_Json_Encoder::encode(array('response' => 'error'));
        } catch (Exception $e) {
            $logger = Zend_Registry::get(VirtualLabs_Exception::ERROR_LOG);
            $logger->err($e->getMessage());
            $logger->err($e->getTraceAsString());
            $this->view->error = $this->view->errorMsg('Ha ocurrido un error al intentar eliminar el registro');
            $this->forward('index');
        }
    }

    public function editAction() {
        $username = $this->getRequest()->getParam('id');
        $this->_debugLog->info($username);

        if (!is_null($username)) {

            $usuario = new VirtualLabs_Admin_Usuario();
            $users = $usuario->getUsuarios(array('*'), array('username' => array('criteria' => '=', 'value' => $username)));

            foreach ($users as $user) {
                $this->_debugLog->info(print_r($user, true));
                $this->view->username = $username;
                $this->view->nombre = $user['nombre'];
                $this->view->apellido = $user['apellido'];
                $this->view->email = $user['email'];
                switch ($user['tipo_usuario']) {
                    case VirtualLabs_Admin_Usuario::ROL_ALUMNO:
                        $this->view->tipoUsuario = "<option value='" . VirtualLabs_Admin_Usuario::ROL_ADMIN . "'>Admin</option>"
                                . "<option value='" . VirtualLabs_Admin_Usuario::ROL_PROFESOR . "'>Profesor</option>"
                                . "<option selected value='" . VirtualLabs_Admin_Usuario::ROL_ALUMNO . "'>Alumno</option>";
                        break;
                    case VirtualLabs_Admin_Usuario::ROL_PROFESOR:
                        $this->view->tipoUsuario = "<option value='" . VirtualLabs_Admin_Usuario::ROL_ADMIN . "'>Admin</option>"
                                . "<option selected value='" . VirtualLabs_Admin_Usuario::ROL_PROFESOR . "'>Profesor</option>"
                                . "<option  value='" . VirtualLabs_Admin_Usuario::ROL_ALUMNO . "'>Alumno</option>";
                        break;
                    case VirtualLabs_Admin_Usuario::ROL_ADMIN:
                        $this->view->tipoUsuario = "<option selected value='" . VirtualLabs_Admin_Usuario::ROL_ADMIN . "'>Admin</option>"
                                . "<option value='" . VirtualLabs_Admin_Usuario::ROL_PROFESOR . "'>Profesor</option>"
                                . "<option value='" . VirtualLabs_Admin_Usuario::ROL_ALUMNO . "'>Alumno</option>";
                        break;
                }

                if (VirtualLabs_Common::USER_ACTIVE ==
                        $user['estado']) {
                    $this->view->activo = 'selected';
                } else if (VirtualLabs_Common::USER_INACTIVE ==
                        $user['estado']) {
                    $this->view->inactivo = 'selected';
                }
            }
        } else {
            $this->view->tipoUsuario = "<option value='" . VirtualLabs_Admin_Usuario::ROL_ADMIN . "'>Admin</option>"
                    . "<option value='" . VirtualLabs_Admin_Usuario::ROL_PROFESOR . "'>Profesor</option>"
                    . "<option value='" . VirtualLabs_Admin_Usuario::ROL_ALUMNO . "'>Alumno</option>";
        }
    }

    public function listAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $usuario = new VirtualLabs_Admin_Usuario();
        $response = array();
        $list = $usuario->getUsuarios(array('username', 'nombre', 'apellido'), array('estado' => array('criteria' =>
                '=', 'value' => 'A')));
        foreach ($list as $user) {
            $response [] = array($this->view->deleteUrl($user['username'], "usuario"), $this->view->editUrl($user['username'], $user['username'], "usuario"),
                $user['apellido'] . ", " . $user['nombre']);
        }
        echo Zend_Json_Encoder::encode($response);
    }

    public function saveAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $usuario = new VirtualLabs_Admin_Usuario();
        $users = $usuario->getUsuarios(array('*'), array('username' => array('criteria' => '=', 'value' => $this->getRequest()->getParam('username'))));
        $this->_debugLog->debug(print_r($users, true));
        if (count($users) > 0) {
            if ($this->getRequest()->getParam('passw')) {
                $data = array('nombre' => $this->getRequest()->getParam('nombre'),
                    'apellido' => $this->getRequest()->getParam('apellido'),
                    'email' => $this->getRequest()->getParam('email'),
                    'passw' => VirtualLabs_Admin_Usuario::getPassword($this->getRequest()->getParam('passw')),
                    'estado' => $this->getRequest()->getParam('estado'),
                    'tipo_usuario' => $this->getRequest()->getParam('tipo_usuario'));
            } else {
                $data = array('nombre' => $this->getRequest()->getParam('nombre'),
                    'apellido' => $this->getRequest()->getParam('apellido'),
                    'email' => $this->getRequest()->getParam('email'),
                    'estado' => $this->getRequest()->getParam('estado'),
                    'tipo_usuario' => $this->getRequest()->getParam('tipo_usuario'));
            }
            $where = array('key' => 'username', 'value' => $this->getRequest()->getParam('username'));
        } else {
            $data = array('username' => $this->getRequest()->getParam('username'),
                'nombre' => $this->getRequest()->getParam('nombre'),
                'apellido' => $this->getRequest()->getParam('apellido'),
                'passw' => VirtualLabs_Admin_Usuario::getPassword($this->getRequest()->getParam('passw')),
                'email' => $this->getRequest()->getParam('email'),
                'estado' => $this->getRequest()->getParam('estado'),
                'tipo_usuario' => $this->getRequest()->getParam('tipo_usuario'));
            $where = null;
        }
        try {
            $usuarioData = $usuario->save(VirtualLabs_Admin_Usuario::TABLE_NAME, $data, $where);
            echo Zend_Json_Encoder::encode($usuarioData);
        } catch (Exception $e) {
            $this->_debugLog->info($e->getMessage());
            $this->_debugLog->info($e->getTraceAsString());
        }
    }

    public function checkusernameAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $usuario = new VirtualLabs_Admin_Usuario();
        $user = $usuario->getUsuario(array('*'), array('username' => array('criteria' => '=', 'value' => $this->getRequest()->getParam('username'))));
        if ($user) {
            echo Zend_Json_Encoder::encode(array('exist' => 'yes'));
        } else {
            echo Zend_Json_Encoder::encode(array('exist' => 'no'));
        }
    }

    public function savemyaccountAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $usuario = new VirtualLabs_Admin_Usuario();
        $userLoggedIn = Zend_Auth::getInstance()->getIdentity();
        $param = Zend_Json_Decoder::decode($this->getRequest()->getParam('param'));

        $user = $usuario->getUsuario(array('*'), array('username' => array('criteria' => '=', 'value' => $userLoggedIn['username'])));
        $this->_debugLog->debug("[myaccount-user]" . print_r($user, true));
        if ($user) {
            $data = array('nombre' => $param['nombre'],
                'apellido' => $param['apellido'],
                'email' => $param['email']);
            if ($param['passw'] && $param['passw'] != "") {
                $data['passw'] = VirtualLabs_Admin_Usuario::getPassword($param['passw']);
            }
            $where = array('key' => 'username', 'value' => $userLoggedIn['username']);
        } else {
            return;
        }
        try {
//            $this->_debugLog->info("[where]" . var_export($where, true));
//            $this->_debugLog->info("[data]" . var_export($data, true));
            $usuarioData = $usuario->save(VirtualLabs_Admin_Usuario::TABLE_NAME, $data, $where);
            echo Zend_Json_Encoder::encode($usuarioData);
        } catch (Exception $e) {
            $this->_debugLog->info($e->getMessage());
            $this->_debugLog->info($e->getTraceAsString());
        }
    }

    public function myaccountAction() {
        $userDao = new VirtualLabs_Admin_Usuario();
        $userLoggedIn = Zend_Auth::getInstance()->getIdentity();
        $user = $userDao->getUsuario(array('nombre', 'apellido', 'username', 'email'), array('username' => array('criteria' => '=', 'value' => $userLoggedIn['username'])));
        $this->_debugLog->debug('[user] : ' . print_r($user, true));
        if ($user) {
            $this->view->nombre = $user['nombre'];
            $this->view->apellido = $user['apellido'];
            $this->view->username = $user['username'];
            $this->view->email = $user['email'];
        }
    }

}

